import 'package:flutter/material.dart';
import 'package:sharing/resources/colors.dart';
import 'dart:async'; // 延迟调用
import 'package:sharing/ui/widget/my_app.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sharing/ui/widget/user_login.dart';

class SplashPage extends StatefulWidget {
  @override
  _SplashPageState createState() => _SplashPageState();
}

class _SplashPageState extends State<SplashPage> {
  Timer _t;
  bool isLogin = false;

  @override
  void initState() {
    super.initState();
    // 获取用户的登录数据
    fetch_login_data();

    _t = Timer(const Duration(seconds: 3), () {
      try {
        if (isLogin) {
          Navigator.of(context).pushAndRemoveUntil(
              new MaterialPageRoute(
                  builder: (BuildContext context) => new MyApp()),
              (Route route) => route == null);
        } else {
          Navigator.of(context).pushAndRemoveUntil(
              new MaterialPageRoute(
                  builder: (BuildContext context) => new Login()),
              (Route route) => route == null);
        }
      } catch (e) {
        print("error $e");
      }
    });
  }

  // 获取用户的登录数据, 如果用户没有登录,  跳转到用户的登录界面
  // 否则跳转到app 的主页
  void fetch_login_data() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String login_info = prefs.getString("authorization");
//    如果获取到用户的登录消息, 返回的数据不为空, 如果没有获取到用户的登录消息,返回的登录消息为空
    isLogin = login_info != null ? true : false;
    print("用户是否已经登录 ${login_info}");
  }

  @override
  void dispose() {
    super.dispose();
    _t.cancel(); //
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      color: AppColor.light,
      child: Padding(
        padding: EdgeInsets.only(top: 150.0),
        child: Column(children: <Widget>[
          Text(
            "悦享悦读",
            style: TextStyle(
              color: AppColor.primary, // 文字的颜色
              fontSize: 36.0, // 字体的大小
              fontWeight: FontWeight.bold, // 字体的权重,..加粗
            ),
          ),
        ]),
      ),
    );
  }
}
